import { API_GetEditorInfo, API_LoginPost } from "./api.js";

class LoginBox {
    loginBox = null;
    loginStatus = 0;
    constructor(parentId) {
        this.loginBox = document.createElement("div");
        this.loginBox.setAttribute("id", "loginBox");
        this.loginBox.setAttribute(
            "style",
            "width:400px; height:300px; background:#000; position: fixed; display:block; left: 50%; margin-left:-200px; top: 50%; margin-top:-300px; z-index: 1000;"
        );

        this.loginBox.innerHTML = `
            <div id="loginTitle" style="width:100%; height:30px; background:#ff0000;"></div>
            <div id="loginBody" style="width:100%; height:calc(100% - 30px); background:#00ff00;">
                <div class="userinfo-item">
                    <span>用户</span>
                    <input id="login_username" type="text" value="" />
                </div>
                <div class="userinfo-item">
                    <span>密码</span>
                    <input id="login_password" type="password" value="" />
                </div>

                <div class="userinfo-item">
                    <div id="loginButton" style="width:200px; text-align:center; height:30px; background:#00fff0;">登录</div>
                </div>
                    <a target="_blank" href="/register.html">注册</a>
            </div>
        `;
        // console.log(this.loginBox);
        document.getElementById(parentId).appendChild(this.loginBox);
        document.getElementById("loginButton").onclick = () => {
            const username = document.getElementById("login_username").value;
            const password = document.getElementById("login_password").value;
            // console.log("登录", username, password);
            if (username === "" || password === "") {
                alert("请输入用户名密码");
                return;
            }

            API_LoginPost(username, password, (res) => {
                if (res.code === 0) {
                    localStorage.setItem("token", res.info["token"]);
                    localStorage.setItem("info", JSON.stringify(res.info));
                    CheckUserInfo();
                    alert("登录成功");
                }
            });
        };
    }
    getDisplay() {
        return this.loginBox.style.display;
    }

    setDisplayNone() {
        this.loginBox.style.display = "none";
    }
    setDisplayBlock() {
        this.loginBox.style.display = "block";
    }
    getLoginStatus() {
        return this.loginStatus;
    }
}
var userInfoDiv = null;
var loginDiv = null;
var loginbox = null;

var onChangeCallback = null;

/**
 *
 * 初始化登录
 * @param {Function|null} onUserInfoChange
 */
function Login_Init(onUserInfoChange = null) {
    if (onUserInfoChange != null) {
        onChangeCallback = onUserInfoChange;
    }
    userInfoDiv = document.getElementById("userInfo");
    loginDiv = document.getElementById("login");
    loginbox = new LoginBox("body");

    userInfoDiv.onclick = function (e) {
        // console.log("userInfoDiv click");
        const menu = POPMenuObject();
        menu.clear();
        menu.addItem("退出登录", null, () => {
            console.log("退出登录");
            localStorage.removeItem("token");
            localStorage.removeItem("info");
            window.location.reload();
        });
        openMask();
        menu.show(e.clientX, e.clientY);
    };

    loginDiv.onclick = function () {
        // if(loginDiv.innerText === '')
        const username = loginDiv.getAttribute("username");
        if (username === "") {
            openMask();
            loginbox.setDisplayBlock();
        }
    };

    localStorage.setItem("info", "");
    setInterval(() => {
        Login_CheckUserInfo();
    }, 8000);
    Login_CheckUserInfo();
}

/** 当用户信息发生变化 */
function onChangeUserInfo(info) {
    // const info = localStorage.getItem('info')
    console.log("change info");
    loginDiv.style.display = "none";
    userInfoDiv.innerText = info.username;
    userInfoDiv.style.display = "inline-block";
    loginbox.loginStatus = 1;
    loginbox.setDisplayNone();
    // ProjectUpdateList();
    if (onChangeCallback != null) {
        onChangeCallback(info);
    }
}

/** 验证token，一般配合定时器 */
function Login_CheckUserInfo() {
    const token = localStorage.getItem("token");
    if (token == null || token == "") {
        loginDiv.style.display = "inline-block";
        return;
    }

    API_GetEditorInfo(token, (res) => {
        if (res.code != 0) {
            localStorage.removeItem("token");
            loginDiv.style.display = "inline-block";
            userInfoDiv.style.display = "none";
            loginbox.loginStatus = 0;

            return;
        } else {
            const infostr = localStorage.getItem("info");
            const newstr = JSON.stringify(res.info);
            if (infostr != newstr) {
                localStorage.setItem("info", newstr);
                onChangeUserInfo(res.info);
            }
        }
    });
}

function Login_GetUserID() {
    const info = localStorage.getItem("info");
    if (info == null || info == "") {
        return "";
    }
    const userInfo = JSON.parse(info);
    return userInfo.user_id;
}

function Login_GetStatus() {
    return loginbox.getLoginStatus();
}

function Login_BoxCancel() {
    if (loginbox.getDisplay() == "block") {
        loginbox.setDisplayNone();
    }
}

function Login_GetToken() {
    const token = localStorage.getItem("token");
    if (token == null || token == "") {
        return "";
    }
    return token;
}

export {
    Login_Init,
    Login_CheckUserInfo,
    Login_GetUserID,
    Login_GetStatus,
    Login_BoxCancel,
    Login_GetToken,
};
